package ludichat.cobbreeding

import com.cobblemon.mod.common.api.pokemon.PokemonProperties
import com.cobblemon.mod.common.api.pokemon.PokemonSpecies
import com.cobblemon.mod.common.api.pokemon.egg.EggGroup
import com.cobblemon.mod.common.api.pokemon.stats.Stats
import com.cobblemon.mod.common.pokemon.FormData
import com.cobblemon.mod.common.pokemon.Species
import ludichat.cobbreeding.components.CobbreedingComponents
import net.minecraft.util.Mth
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.component.CustomModelData
import net.minecraft.core.component.DataComponents

object EggUtilities {
    @JvmStatic
    fun selectEggItem(pokemon: FormData): ItemStack {
        if (pokemon.species.showdownId() == "manaphy") return ItemStack(Cobbreeding.EGG_ITEMS["manaphy_egg"]!!.get())

        try {
            val type1 = pokemon.primaryType
            val type2 = pokemon.secondaryType
            if (type2 != null && type1 != type2) return ItemStack(Cobbreeding.EGG_ITEMS[type1.name + "_" + type2.name + "_pokemon_egg"]!!.get())

            return ItemStack(Cobbreeding.EGG_ITEMS[type1.name + "_pokemon_egg"]!!.get())
        } catch (_: NullPointerException) {}

        return ItemStack(Cobbreeding.EGG_ITEMS["pokemon_egg"]!!.get())
    }

    @JvmStatic
    fun setEggQuality(eggItem: ItemStack, properties: PokemonProperties) {
        var customModelData = 0
        
        // 计算IV品质
        var perfectIVs = 0
        if (properties.ivs != null) {
            val ivs = properties.ivs!!
            val stats = listOf(Stats.HP, Stats.ATTACK, Stats.DEFENCE, Stats.SPECIAL_ATTACK, Stats.SPECIAL_DEFENCE, Stats.SPEED)
            perfectIVs = stats.count { (ivs[it] ?: 0) == 31 }
        }
        
        val isShiny = properties.shiny == true
        
        // 设置CustomModelData
        customModelData = when {
            isShiny && perfectIVs >= 6 -> 7  // 闪光6V
            isShiny && perfectIVs >= 5 -> 6  // 闪光5V
            isShiny && perfectIVs >= 4 -> 5  // 闪光4V
            isShiny -> 4                     // 闪光
            perfectIVs >= 6 -> 3            // 6V
            perfectIVs >= 5 -> 2            // 5V
            perfectIVs >= 4 -> 1            // 4V
            else -> 0                       // 普通
        }
        
        // 设置品质标签，方便其他模组过滤
        val qualityTag = when {
            isShiny && perfectIVs >= 6 -> "shiny_6v"
            isShiny && perfectIVs >= 5 -> "shiny_5v"
            isShiny && perfectIVs >= 4 -> "shiny_4v"
            isShiny -> "shiny"
            perfectIVs >= 6 -> "6v"
            perfectIVs >= 5 -> "5v"
            perfectIVs >= 4 -> "4v"
            else -> "normal"
        }
        eggItem.set(CobbreedingComponents.EGG_QUALITY.get(), qualityTag)
        
        // 调试输出
//        Cobbreeding.LOGGER.warn("=== setEggQuality 调试 ===")
//        Cobbreeding.LOGGER.warn("perfectIVs: $perfectIVs")
//        Cobbreeding.LOGGER.warn("isShiny: $isShiny")
//        Cobbreeding.LOGGER.warn("计算出的CustomModelData: $customModelData")
//        Cobbreeding.LOGGER.warn("品质标签: $qualityTag")
        
        if (customModelData > 0) {
            eggItem.set(DataComponents.CUSTOM_MODEL_DATA, CustomModelData(customModelData))
//            Cobbreeding.LOGGER.warn("已设置CustomModelData: $customModelData")
        } else {
//            Cobbreeding.LOGGER.warn("CustomModelData为0，未设置")
        }
//        Cobbreeding.LOGGER.warn("=======================")
    }

    @JvmStatic
    fun calculateTimer(pokemon: Species): Int {
        return Mth.floor(pokemon.eggCycles * PokemonEgg.DEFAULT_TIMER * Cobbreeding.config.eggHatchMultiplier)
    }

    @JvmStatic
    fun getEggFromPokemonProperties(properties: PokemonProperties, timer: Int? = null) : ItemStack?
    {
        val species = PokemonSpecies.getByName(properties.species!!)
        val eggItem: ItemStack
        if (species != null)
        {
            var form = species.standardForm
            if (properties.form != null)
                form = species.getFormByShowdownId(properties.form!!)

            if (Cobbreeding.config.customColors)
                eggItem = selectEggItem(form)
            else
                eggItem = ItemStack(Cobbreeding.EGG_ITEMS.get("pokemon_egg")!!.get())

            // 设置蛋品质外观
            setEggQuality(eggItem, properties)

            // Setting Pokemon Properties
            eggItem.set(CobbreedingComponents.EGG_INFO.get(), properties.asString())
            // Setting the egg timer
            if (timer == null)
                eggItem.set<Int>(
                        CobbreedingComponents.TIMER.get(),
                        calculateTimer(species)
                )
            else
                eggItem.set<Int>(
                        CobbreedingComponents.TIMER.get(),
                        timer
                )

            return eggItem
        }
        else if (properties.species == "random")
        {
            eggItem = ItemStack(Cobbreeding.EGG_ITEMS["pokemon_egg"]!!.get())
            eggItem.set(CobbreedingComponents.TIMER.get(), calculateTimer(PokemonSpecies.random()))
            eggItem.set(CobbreedingComponents.EGG_INFO.get(), properties.asString())
            return eggItem
        }

        return null
    }

    fun randomEgg() : FormData
    {
        // Choosing a random species
        var species = PokemonSpecies.random()
        // Rolling until the pokemon is allowed by the configs
        while (!isRandomSpeciesAllowed(species))
            species = PokemonSpecies.random()

        // Choosing a random form
        if (species.forms.count() > 0)
        {
            var form = species.forms.random()
            return BreedingUtilities.getBaby(form)
        }

        return BreedingUtilities.getBaby(species.standardForm)
    }

    private fun isRandomSpeciesAllowed(species: Species) : Boolean
    {
        val isLegendary = species.labels.contains("legendary") || species.labels.contains("mythical")
        val isParadox = species.labels.contains("paradox")
        val isUltraBeast = species.labels.contains("ultra_beast")
        val isUndiscovered = species.eggGroups.contains(EggGroup.UNDISCOVERED)

        // The pokemon can normally be obtained via egg
        if (!isLegendary && !isParadox && !isUltraBeast && !isUndiscovered)
            return true

        // Legendary / Mythical check
        if (Cobbreeding.config.dittoAndDittoAllowLegendary && isLegendary)
            return true
        // Paradox check
        if (!isLegendary && Cobbreeding.config.dittoAndDittoAllowParadox && isParadox)
            return true
        // Ultra Beast check
        if (!isLegendary && !isParadox && Cobbreeding.config.dittoAndDittoAllowUltraBeast && isUltraBeast)
            return true
        // Undiscovered check
        if (!isLegendary && !isParadox && !isUltraBeast && Cobbreeding.config.dittoAndDittoAllowUndiscovered)
            return true


        // Default return is false because some check may be overlapping (eg "legendary" and "undiscovered")
        return false
    }

    private fun isEgg(itemStack: ItemStack): Boolean
    {
        return itemStack.item is PokemonEgg
    }

    @JvmStatic
    fun areSameEgg(a: ItemStack, b: ItemStack): Boolean
    {
        if (isEgg(a) && isEgg(b))
        {
            val comp_a = a.getOrDefault(CobbreedingComponents.POKEMON_PROPERTIES.get(), 0)
            val comp_b = b.getOrDefault(CobbreedingComponents.POKEMON_PROPERTIES.get(), 0)
            if (comp_a.equals(comp_b))
                return true
        }
        return false
    }
}